<!DOCTYPE html>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="lib/jquery.min.2.1.4.js"></script>
<title>CSRF Attck!</title>
</head>

<body>
     <div>
      <input id="btn" type="button" value="go without token" onclick="fire()" />
     </div>
     
     <div>
      <input id="btn" type="button" value="go with token" onclick="fireToken()" />
     </div>
	 
    <div>
	      server response is: <br><span id="showdata" type="text"></span>
	</div>
</body>
<script type="text/javascript">
    var host = "localhost:7777";
    function fire(){
    	$.ajax({
			url: 'http://'+host+'/csrf/form', 
            method: 'POST',
    		data: {
    			csrf_token:"haha"
    		},
    		//no problem
            success: function (data) {
            	alert(data);
            },
            error: function (error) {
                alert('error:'+error.responseText);
            }
        });
    }
    
    function fireToken(){
    	$.ajax({
			url: 'http://'+host+'/csrf', 
            method: 'GET',
            success: function (data,status,xhr) {
            	//跨域的js只能取到部分响应头：Expires、Content-Language、Content-Type
            	//console.log(xhr);
            	console.log("允许获取的响应头："+xhr.getAllResponseHeaders());
            	//跨域的js无法获取响应头中的csrf_token信息
            	console.log("从响应头中获取csrf_coken："+xhr.getResponseHeader("csrf_coken"));
            	var html = $.parseHTML(data);
            	var csrf_token = data;
            	//console.log(document.cookie);
            	alert("可以获取token: "+csrf_token+ " 但无法关联源站的session。"+document.cookie);
		    	$.ajax({
					url: 'http://'+host+'/csrf/form', 
		            method: 'POST',
		            //跨域请求禁止修改请求头
		            //headers:{
		                //csrf_token:csrf_token
		            //},
		    		data:{
		    			csrf_token:csrf_token
		    		},
		            success: function (data) {
		            	console.log(data);
		            	if(data){
							alert(data);
		            	}
		            	else{
			                alert('error:'+data);
		            	}
		            },
		            error: function (error) {
		                alert('error:'+error.responseText);
		            }
		        });
            },
            error: function (error) {
            	console.log(error);
                alert('error!');
            }
        });
    }
</script>
</html>
